﻿using System;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class SecondaryButton:MonoBehaviour
{
    [SerializeField] private ExpandUI expandUI;
    [SerializeField] private Transform buttonGroup;
    [SerializeField] private GameObject buttonPrefab;

    private Button primaryButton;

    private void Awake()
    {
        primaryButton = GetComponent<Button>();
    }
    private void Start()
    {
        primaryButton.onClick.AddListener(() =>
        {
            expandUI.SwithPanel();
        });
    }
    public void PrimaryButton(string name)
    {
        primaryButton.GetComponentInChildren<Text>().text = name;
    }
    public void PrimaryButton(ActionItem action)
    {
        primaryButton.GetComponentInChildren<Text>().text = action.Name;
        primaryButton.onClick.AddListener(()=> 
        {
            action.Action?.Invoke();
        });
    }
    public void Initialize(List<Action> actions)
    {
        GenerateButtons(actions);
    }
    public void Initialize(List<ActionItem> actions)
    {
        GenerateButtons(actions);
    }
    private void GenerateButtons(List<ActionItem> actionItems)
    {
        ClearButtons(); // 清空当前按钮

        for (int i = 0; i < actionItems.Count; i++)
        {
            var button = Instantiate(buttonPrefab, buttonGroup);
            int index = i; // 防止闭包问题
            button.GetComponentInChildren<Text>().text = actionItems[index].Name;

            // 为按钮设置对应的 Action
            button.GetComponent<Button>().onClick.AddListener(() => actionItems[index].Action());
        }
    }
    private void GenerateButtons(List<Action> actions)
    {
        ClearButtons(); // 清空当前按钮

        for (int i = 0; i < actions.Count; i++)
        {
            var button = Instantiate(buttonPrefab, buttonGroup);
            int index = i; // 防止闭包问题
            button.GetComponentInChildren<Text>().text = "按钮 " + (index + 1);

            // 为按钮设置对应的 Action
            button.GetComponent<Button>().onClick.AddListener(() => actions[index]());
        }
    }
    private void ClearButtons()
    {
        foreach (Transform child in buttonGroup)
        {
            Destroy(child.gameObject);
        }
    }

}

